<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\LeaderApproachLog;

use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use app\admin\model\Chargedep;
use app\admin\model\Admin;
/**
 *
 *
 * @icon fa fa-circle-o
 */
class LeaderApproach extends Backend
{

    /**
     * LeaderApproach模型对象
     * @var \app\admin\model\LeaderApproach
     */
    protected $model = null;
    protected $relationmodel = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\LeaderApproach;
        $this->relationmodel = new \app\admin\model\LeaderApproachContent;

        $this->relationtTable = 'contents';
        $this -> assign('leaders',getSelectList('leader'));
        $this -> assign('chargeDeps',getSelectList('chargedep'));
        $this->assign('isSuperAdmin',$this->auth->isSuperAdmin());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        $this->whereExtend['status'] = 0; //未在审核中
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $this->sortExtend = 'number desc';
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with($this->relationtTable)
                ->where($where)
                ->where($this->whereExtend)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with($this->relationtTable)
                ->where($where)
                ->where($this->whereExtend)
                ->order($this->sortExtend)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

             // echo $this->model->getLastSql();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    public function add(){
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                    // var_dump($params);exit();
                   // 区领导
                $leader_ids = '';
                $leader_names = '';
                if (isset($params['leader_ids'])) {
                    foreach($params['leader_ids'] as $key => $value)
                    {
                        $leader_ids .= $value.",";
                        $leader_names .= getSelectText('leader',$value).',';
                    }
                    $leader_ids = substr($leader_ids,0,strlen($leader_ids)-1);
                    $leader_names = substr($leader_names,0,strlen($leader_names)-1);
                }

                $params['leader_ids'] = $leader_ids;
                $params['leader_names'] = $leader_names;





                // pr($params);exit();

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                     // pr($params);exit();

                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    public function edit($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            exit($ids);
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $updateData = [];
                // 区领导
                $leader_ids = '';
                $leader_names = '';
                if (isset($params['leader_ids'])) {
                    foreach($params['leader_ids'] as $key => $value)
                    {
                        $leader_ids .= $value.",";
                        $leader_names .= getSelectText('leader',$value).',';
                    }
                    $leader_ids = substr($leader_ids,0,strlen($leader_ids)-1);
                    $leader_names = substr($leader_names,0,strlen($leader_names)-1);

                    $updateData['leader_ids'] = $leader_ids;
                    $updateData['leader_names'] = $leader_names;
                }
                $params['leader_ids'] = $leader_ids;
                $params['leader_names'] = $leader_names;

                if(isset($params['out_date']))
                    $updateData['out_date'] = $params['out_date'];

                if(isset($params['out_city']))
                    $updateData['out_city'] = $params['out_city'];

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    // pr($params);exit();

                    // 更新leader_approach_content表
                    $row_leader = $this->relationmodel->where(['leader_approach_id'=>$row->id])->select();
                    if(!empty($updateData)&&!empty($row_leader))
                      $ret = $this->relationmodel->where(['leader_approach_id'=>$row->id])->update($updateData);


                    $result =  $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assign('row',$row);
        return $this->view->fetch();
    }


    public function addcontent($ids){
        $row = $this->model->get($ids);
        if(!$row)
            $this->error('记录不存在');
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params['leader_approach_id'] = $ids;
                $params['leader_ids'] = $row['leader_ids'];
                $params['leader_names'] = $row['leader_names'];
                $params['out_date'] = $row['out_date'];
                $params['out_city'] = $row['out_city'];
                $chargedep_ids = '';
                $chargedep_names = '';
                if (isset($params['chargedep_ids'])&&is_array($params['chargedep_ids'])) {
                   $chargedep_ids = implode(",",$params['chargedep_ids']);
                   $chargedep_names = getSelectText('chargedep',$params['chargedep_ids']);
                }
                $params['chargedep_ids'] = $chargedep_ids;
                $params['chargedep_names'] = $chargedep_names;
                $result = false;

                $result = $this->relationmodel ->allowField(true)->save($params);
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
        }
        $this->assign('row',$row);
        return $this->view->fetch();
    }

    public function editcontent($ids){
        $row = $this->relationmodel->get($ids);
        if(!$row)
            $this->error('记录不存在');
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $result = false;
                if(!$this->auth->isSuperAdmin())
                {
                    if($params['project_progress']){
                        $params['tmp_project_progress']=$params['project_progress'];
                        $params['project_progress']=$row['project_progress'];
                    }
                    if($params['project_problem']){
                        $params['tmp_project_problem']=$params['project_problem'];
                        $params['project_problem']= $row['project_problem'];
                    }
                    if($params['project_nextplan']){
                        $params['tmp_project_nextplan']=$params['project_nextplan'];
                        $params['project_nextplan']=$row['project_nextplan'];
                    }
                    $params['status'] = 1;
                }

                $result = $row ->allowField(true)->save($params);
                if ($result !== false) {
                    if(!$this->auth->isSuperAdmin())
                    {
                        // 先判断 nsig_leader_approach_content 是不是全为1，更新nsig_leader_approach 表为1
                        $info = $this->relationmodel->where(['status'=>0,'leader_approach_id'=>$row->leader_approach_id])->find();
                        if(empty($info))
                        {
                            // 更新主表
                            $row_leader = $this->model->get($row->leader_approach_id);
                            $row_leader->status = 1;
                            $row_leader->save();
                        }
                    }
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
        }

        $this->assign('row',$row);
        return $this->view->fetch();
    }

    /**
     * 审核
     */
    public function checkedit($ids = null){
        $row = $this->relationmodel->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $field = ['project_progress','project_problem','project_nextplan'];
        if ($this->request->isPost()) {

            $data = [];
            foreach ($field as  $value) {
                $data[$value] = $row['tmp_'.$value];
                $data['tmp_'.$value] = null;
            }
            $data['status'] = 0;
            $result = false;
            $result = $row->allowField(true)->save($data);
            if ($result !== false) {
                // 先判断 nsig_leader_approach_content 是不是有为0，更新nsig_leader_approach 表为0
                // $info = $this->relationmodel->where(['status'=>1,'id'=>$ids])->find();
                // if(empty($info)){
                    $row_leader= $this->model->get($row->leader_approach_id);
                    $update['status'] = 0;
                    $row_leader->allowField(true)->save($update);
                // }
                // 完事添加nsig_leader_approach_log 记录
                $leader_log = [
                    'leader_approach_id'=>$row->leader_approach_id,
                    'operator_id'=>$this->auth->id,
                    'operator_nickname'=>$this->auth->nickname,
                    'create_time'=>time(),
                    'update_time'=>time(),
                ];
                LeaderApproachLog::insert($leader_log);

                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->assignconfig('ids',$ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 导入
     */
    public function importleader()
    {
        $model = new \app\admin\model\LeaderApproachContent();
        if($this->request->isPost()){
            $file = $this->request->request('filepath');
            // $this->importExcel_leader($file);
            $baseField = [1=>'leader_names',2=>'out_date',3=>'out_city',4=>'company',5=>'project_summary',6=>'chargedep_names',7=>'project_progress',8=>'project_problem',9=>'project_nextplan'];
            $insert = $this->baseImportRead($baseField,'',3,$file);

            // $insert_new = [];
            // $sort = 0;
            $time = time();
            $update = [];
            foreach ($insert as $v){

                // 领导，日期，城市
                if(!empty($v['leader_names']) && !empty($v['out_date']) && !empty($v['out_city']))
                {
                    // 判断是否存在
                    $row=$this->model->where(['leader_names'=>trim($v['leader_names']),'out_date'=>$v['out_date'],'out_city'=>$v['out_city']])->find();
                    if(isset($row))
                    {
                        //再判断公司名是否存在
                        $row_leader = $this->relationmodel->where(['leader_approach_id'=>$row->id,'company'=>$v['company']])->find();
                        if(!isset($row_leader))
                        {
                            // 责任单位
                            $chargedep_info = Chargedep::where(['name'=>$v['chargedep_names']])->find();
                            if(!empty($chargedep_info))
                                $chargedep_ids = $chargedep_info['id'];
                            else
                                $chargedep_ids = '';

                            $insert_new = [
                                'leader_approach_id' => $row->id,
                                'leader_ids'         => $row->leader_ids,
                                'leader_names'       => $row->leader_names,
                                'out_date'           => $row->out_date,
                                'out_city'           => $row->out_city,
                                'company'            => $v['company'],
                                'project_summary'    => $v['project_summary'],
                                'chargedep_ids'      => $chargedep_ids,
                                'chargedep_names'    => $v['chargedep_names'],
                                'project_progress'   => $v['project_progress'],
                                'project_problem'    => $v['project_problem'],
                                'project_nextplan'   => $v['project_nextplan'],
                                'create_time'        => $time,
                                'update_time'        => $time,
                            ];
                            $model->save($insert_new);
                        }
                    }else{
                        $leader_ids = '';
                        // 先往nsig_leader_approach添加，后往nsig_leader_approach_content添加
                        $leader_names_array = explode(",",$v['leader_names']);
                        // var_dump($leader_names_array);
                        // echo "<br/>";
                        foreach($leader_names_array as $k => $val)
                        {
                            $chargedep_info = Admin::where(['nickname'=>$val])->find();
                            // echo $chargedep_info."###<br/>";
                            if(isset($chargedep_info))
                                $leader_ids .= $chargedep_info['id'].',';
                                // $leader_ids = substr($leader_ids,0,strlen($leader_ids)-1);
                            // $leader_ids = substr($leader_ids,0,strlen($leader_ids)-1);
                            // var_dump($chargedep_info)."<br/>";
                        }
                        if(!empty($leader_ids))
                             $leader_ids = substr($leader_ids,0,strlen($leader_ids)-1);
                        // echo $leader_ids."@@@@<br/>";
                        $insert = [
                            'leader_ids'    => $leader_ids,
                            'leader_names'  => $v['leader_names'],
                            'out_date'      => $v['out_date'],
                            'out_city'      => $v['out_city'],
                            'create_time'   => $time,
                            'update_time'   => $time,
                        ];
                        $ret = $this->model->save($insert);

                        // 更新content 表
                        if($ret){
                            // 责任单位
                            $chargedep_info = Chargedep::where(['name'=>$v['chargedep_names']])->find();
                            if(!empty($chargedep_info))
                                $chargedep_ids = $chargedep_info['id'];
                            else
                                $chargedep_ids = '';

                            $insert_new_content = [
                                'leader_approach_id' => $this->model->id,
                                'leader_ids'         => $leader_ids,
                                'leader_names'       => $v['leader_names'],
                                'out_date'           => $v['out_date'],
                                'out_city'           => $v['out_city'],
                                'company'            => $v['company'],
                                'project_summary'    => $v['project_summary'],
                                'chargedep_ids'      => $chargedep_ids,
                                'chargedep_names'    => $v['chargedep_names'],
                                'project_progress'   => $v['project_progress'],
                                'project_problem'    => $v['project_problem'],
                                'project_nextplan'   => $v['project_nextplan'],
                                'create_time'        => $time,
                                'update_time'        => $time,
                            ];
                            $model->save($insert_new_content);
                        }
                    }

                }
                // echo $v['leader_names']."#######<br>";
            }

            $this->success('导入成功');
            exit();

        }
        $expurl = '/template/leader.xlsx';

        $this->assign('expurl', $expurl);
        return $this->view->fetch('import');
    }

    protected function baseImportRead($baseField=[],$type,$startRow = 2,$file){
        set_time_limit(0);
        ini_set('memory_limit', '1280M');
        // $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }

        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }
        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }

            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行

            $hotelName = '';
            if($this -> auth -> obj_id){
                $hotelName = (\app\admin\model\Hotel::get($this -> auth->obj_id)) -> name;
            }

            for ($currentRow = $startRow; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                foreach ($baseField as $fieldKey => $fieldValue) {
                    $val = $currentSheet->getCellByColumnAndRow($fieldKey, $currentRow)->getValue();
                    $values[] = trim(is_object($val) ? $val->__toString() : ($val == null ? '' : trim($val)));
                }

                $temp = array_combine($baseField, $values);
                if($type){
                    $temp['hotel_id'] = $this -> auth -> obj_id;
                    $temp['hotel_name'] = $hotelName;
                    $temp['status'] = 2;
                    $temp['type'] = $type;
                }
                $insert[] = $temp;

            }

        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        //是否包含admin_id字段
        $has_admin_id = false;
        foreach ($fieldArr as $name => $key) {
            if ($key == 'admin_id') {
                $has_admin_id = true;
                break;
            }
        }
        if ($has_admin_id) {
            $auth = Auth::instance();
            foreach ($insert as &$val) {
                if (!isset($val['admin_id']) || empty($val['admin_id'])) {
                    $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                }
            }
        }
        return $insert;
    }


}
